package cn.example.common.protocol.modules;

import org.artifact.core.lang.IServer;
import org.artifact.core.context.session.ISession;
import org.artifact.core.context.packet.IPacket;
import cn.hutool.core.map.MapProxy;
import java.util.function.Consumer;
import java.util.Collection;
import java.util.Map;
import java.util.List;
import org.artifact.core.constant.ArtifactErrorCode;
import org.artifact.core.exception.ArtifactExceptionUtil;
import org.artifact.core.lang.IModule;
import cn.example.common.protocol.structs.*;

@SuppressWarnings("unchecked")
public interface TaskModule extends IModule{
	
	default int getModuleId(){
		return 13701;
	}
	
	/** 分发  */
	default Consumer<IPacket> disp(ISession session,IPacket packet) {
		switch (packet.getMethodId()) {
			case 16408:{
				return submit(session,packet);
			}
			case 29997:{
				return sendTask(session,packet);
			}
			default:
				throw ArtifactExceptionUtil.error(ArtifactErrorCode.NOT_FOND_ACTION);
		}
	}	


	/** 提交任务 */
	default Consumer<IPacket> submit(ISession session,IPacket packet) {
		MapProxy proxy = MapProxy.create(packet.getBody());
		long id = proxy.getLong(3355);
		return submit(session, id);
	}
	
	/** 提交任务 */
	Consumer<IPacket> submit(ISession session, long id);
	
	default Consumer<IPacket> _submit(ISession session){
		return (IPacket packet) -> {
                if (packet == null){
                    packet = IServer.me().getContext().getPacketFactory().create();
                    packet.setCmd(13701 << 16 ^ 16408);
                } else {
                    packet.getBody().clear();
                }

				session.sendPacket(packet);
			};
	}
	/** 发送任务 */
	default Consumer<IPacket> sendTask(ISession session,IPacket packet) {
		MapProxy proxy = MapProxy.create(packet.getBody());
		TaskDTO task = (TaskDTO)proxy.get(3552645);
		return sendTask(session, task);
	}
	
	/** 发送任务 */
	Consumer<IPacket> sendTask(ISession session, TaskDTO task);
	
	default Consumer<IPacket> _sendTask(ISession session){
		return (IPacket packet) -> {
                if (packet == null){
                    packet = IServer.me().getContext().getPacketFactory().create();
                    packet.setCmd(13701 << 16 ^ 29997);
                } else {
                    packet.getBody().clear();
                }

				session.sendPacket(packet);
			};
	}
	
	
	/** 更新任务 */
	default void update(ISession session, List<TaskDTO> tasks){
		IPacket packet = IServer.me().getContext().getPacketFactory().create();
		packet.setCmd(13701 << 16 ^ 14537);
		packet.getBody().put(110132110,tasks);
		session.sendPacket(packet);
	}
	
	default void update(Collection<ISession> sessions, List<TaskDTO> tasks){
		IPacket packet = IServer.me().getContext().getPacketFactory().create();
		packet.setCmd(13701 << 16 ^ 14537);
		packet.getBody().put(110132110,tasks);
		for (ISession session : sessions) {
			session.sendPacket(packet);
		}
	}
	
}